﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DataController.ViewModels;
using Primitive.Mvvm.Framework.Interfaces;

namespace UIController.Views
{
    public partial class BottomView : UserControl, IWindowContainer
    {
        private BottomViewModel _model;
        public BottomView()
        {
            InitializeComponent();
        }

        public bool Initialize(IModel model, IMediator mediator, List<Exception> exceptions)
        {
            _model = new BottomViewModel(model, mediator);
            _model.RefreshViewFunc = OnRefresh;
            return Refresh(exceptions);
        }

        private bool OnRefresh(IViewCallback arg)
        {
            if (!_model.CanRefreshView(arg))
                return false;

            var listExc = new List<Exception>();
            var res = Refresh(listExc);
            if (listExc.Count > 0)
            {
                var ecx = new AggregateException("Refresh exception in BottomView", listExc);
                throw ecx;
            }

            return res;
        }

        private bool Refresh(List<Exception> exceptions)
        {
            try
            {
                if (!string.IsNullOrEmpty(_model.TaskNote))
                {
                    textBox1.Text = _model.TaskNote;
                }

                return true;
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }

            return false;
        }

        public void Clear(out Exception exception)
        {
            exception = null;
            textBox1.Text = string.Empty;
            _model = null;
        }
    }
}
